#!ruby
require 'xmlrpc/client'
require 'csv'

# Trac
tracUser = ENV["TM_TRACUSER"]
tracPassword = ENV["TM_TRACPASSWORD"]    
tracUrl = ENV["TM_TRACURL"]
                                                                      
# Init tracServer client 
tracServer = XMLRPC::Client.new2(tracUrl)
tracServer.user = tracUser
tracServer.password = tracPassword
pageStruct = { "author" => tracUser }

# wiki page vars
templateName = "UiCyclopediaTemplate"
imageTemplateName = "UiCyclopediaTemplateImageSection"

# CSV filename        
listFile = "components.csv"

# Wiki tokens...               
imageMacro = "[[Image(${url})]]\n\n"
sourceStubPath = "source:/flexdev/project/trunk/build/flex/src"
imageSourcePath = "source:/flexdev/sandbox/ui_alpha/UiComponentCyclopedia/_images/"

# template tokens
urlToken = "${url}"
componentToken = "${component.name}"
sourceToken = "${source.class}"
asdocToken = "${asdoc.url}"
imagesToken = "${images}"    
                          
# Parse CSV and build pages...                    
                          
CSV.open(listFile, 'r') do |row|   
  # get template  
  tempWikiPage = tracServer.call("wiki.getPage", templateName) 
  # replace heading
  tempWikiPage.sub!(componentToken, row[0])
  # replace source path
  tempWikiPage.sub!(sourceToken, "#{sourceStubPath}#{row[1]}")
  # replace asDoc link
  tempWikiPage.sub!(asdocToken, row[2])
  
  # Image section
  if row[3].data.to_i > 0 then
    # more than 0 images specified...
    
    # Get image section template 
    tempImageSection = tracServer.call("wiki.getPage", imageTemplateName)
    
    # Loop number of images...
    row[3].data.to_i.times do |n|
      # Append Image() macros to the Image Section Template
      tempImageSection << imageMacro.sub(urlToken, "#{imageSourcePath}#{row[0]}_#{n+1}.png" )      
    end                                                                                      
    
    # Add image section to the template
    tempWikiPage.sub!(imagesToken, tempImageSection)
  else
    # otherwise remove the image section token from the page.
    tempWikiPage.sub!(imagesToken, '')
  end                                                        
    
  tracServer.call("wiki.putPage", row[0], tempWikiPage, pageStruct) 
  
  # Debug message
  print "\n#{tempWikiPage}\n"
end                     



